<template>
  <div class="app-container">
    <el-form 
      :model="queryParams" 
      ref="queryForm" 
      size="small" 
      :inline="true" 
      v-show="showSearch" 
      class="api-search-form">
      <el-card shadow="hover" class="search-card">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="API ID">
        <el-input
          v-model="queryParams.apiId"
          placeholder="请输入API ID"
          clearable
                prefix-icon="el-icon-search"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="用户ID">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="API密钥">
        <el-input
          v-model="queryParams.apiKey"
                placeholder="请输入API密钥"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="请求IP">
        <el-input
          v-model="queryParams.ip"
          placeholder="请输入请求IP"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="调用状态">
              <el-select v-model="queryParams.status" placeholder="请选择调用状态" clearable style="width: 100%">
                <el-option label="成功" :value="1" />
                <el-option label="失败" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="响应时间">
              <el-input-number
          v-model="queryParams.responseTime"
                placeholder="响应时间(ms)"
                :min="0"
                style="width: 100%"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-form-item class="search-buttons">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="card-title">API调用记录</span>
        <el-button-group style="float: right;">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['interfaces:interfaceCallLogs:add']"
        >新增</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['interfaces:interfaceCallLogs:edit']"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['interfaces:interfaceCallLogs:remove']"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['interfaces:interfaceCallLogs:export']"
        >导出</el-button>
        </el-button-group>
      </div>

      <el-table
        v-loading="loading"
        :data="interfaceCallLogsList"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{background:'#f5f7fa'}"
        highlight-current-row>
        <el-table-column type="selection" width="55" align="center" fixed="left"/>
        <el-table-column label="日志ID" align="center" prop="id" width="80" fixed="left"/>
        <el-table-column label="API ID" align="center" prop="apiId" width="80"/>
        <el-table-column label="用户ID" align="center" prop="userId" width="80"/>
        <el-table-column label="API密钥" align="center" prop="apiKey" min-width="200" show-overflow-tooltip/>
        <el-table-column label="请求IP" align="center" prop="ip" width="140"/>
        <el-table-column label="调用状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="mini">
              {{ scope.row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="错误信息" align="center" prop="errorMsg" min-width="200" show-overflow-tooltip/>
        <el-table-column label="请求参数" align="center" prop="requestParams" min-width="200" show-overflow-tooltip/>
        <el-table-column label="响应时间" align="center" prop="responseTime" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.responseTime > 1000 ? 'danger' : scope.row.responseTime > 500 ? 'warning' : 'success'" size="mini">
              {{ scope.row.responseTime }}ms
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['interfaces:interfaceCallLogs:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['interfaces:interfaceCallLogs:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>

    <!-- 添加或修改API调用记录对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="600px" 
      append-to-body
      :close-on-click-modal="false"
      :destroy-on-close="true"
      class="api-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="API ID" prop="apiId">
          <el-input v-model="form.apiId" placeholder="请输入API ID" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="API密钥" prop="apiKey">
              <el-input v-model="form.apiKey" placeholder="请输入API密钥" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="请求IP" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入请求IP" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调用状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择调用状态" style="width: 100%">
                <el-option label="成功" :value="1" />
                <el-option label="失败" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
        <el-form-item label="错误信息" prop="errorMsg">
              <el-input v-model="form.errorMsg" type="textarea" :rows="3" placeholder="请输入错误信息" />
        </el-form-item>
          </el-col>
          <el-col :span="24">
        <el-form-item label="请求参数" prop="requestParams">
              <el-input v-model="form.requestParams" type="textarea" :rows="3" placeholder="请输入请求参数" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="响应时间" prop="responseTime">
              <el-input-number v-model="form.responseTime" :min="0" controls-position="right" style="width: 100%" placeholder="请输入响应时间(ms)"/>
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitForm" :loading="submitLoading">确 定</el-button>
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInterfaceCallLogs, getInterfaceCallLogs, delInterfaceCallLogs, addInterfaceCallLogs, updateInterfaceCallLogs } from "@/api/interfaces/interfaceCallLogs";

export default {
  name: "InterfaceCallLogs",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // API调用记录表格数据
      interfaceCallLogsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        apiId: null,
        userId: null,
        apiKey: null,
        ip: null,
        status: null,
        errorMsg: null,
        requestParams: null,
        responseTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        apiId: [
          { required: true, message: "API ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        apiKey: [
          { required: true, message: "调用的API密钥不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询API调用记录列表 */
    getList() {
      this.loading = true;
      
      // 创建一个干净的查询对象，避免嵌套参数
      const query = {};
      
      // 处理业务查询参数
      if (this.queryParams.apiId) query.apiId = this.queryParams.apiId;
      if (this.queryParams.userId) query.userId = this.queryParams.userId;
      if (this.queryParams.apiKey) query.apiKey = this.queryParams.apiKey;
      if (this.queryParams.ip) query.ip = this.queryParams.ip;
      if (this.queryParams.status !== null && this.queryParams.status !== undefined) query.status = this.queryParams.status;
      if (this.queryParams.errorMsg) query.errorMsg = this.queryParams.errorMsg;
      if (this.queryParams.requestParams) query.requestParams = this.queryParams.requestParams;
      if (this.queryParams.responseTime) query.responseTime = this.queryParams.responseTime;
      
      // 直接添加分页参数（不要放在params中嵌套）
      query.pageNum = this.queryParams.pageNum;
      query.pageSize = this.queryParams.pageSize;
      
      console.log('分页请求参数:', query);
      
      // 发送包含分页参数的请求
      listInterfaceCallLogs(query).then(response => {
        this.interfaceCallLogsList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取数据失败:', error);
        this.loading = false;
        this.$message.error('获取数据失败，请刷新页面重试');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        apiId: null,
        userId: null,
        apiKey: null,
        ip: null,
        status: null,
        errorMsg: null,
        requestParams: null,
        responseTime: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加API调用记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInterfaceCallLogs(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改API调用记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInterfaceCallLogs(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInterfaceCallLogs(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除API调用记录编号为"' + ids + '"的数据项？').then(function() {
        return delInterfaceCallLogs(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('interfaces/interfaceCallLogs/export', {
        ...this.queryParams
      }, `interfaceCallLogs_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.api-search-form {
  .search-card {
    margin-bottom: 20px;
    ::v-deep .el-card__body {
      padding: 15px 20px 0;
    }
  }
  ::v-deep .el-form-item {
    margin-bottom: 15px;
    .el-form-item__label {
      font-weight: normal;
      color: #606266;
    }
  }
  .search-buttons {
    text-align: right;
    margin-right: 0;
  }
}

.box-card {
  margin-bottom: 20px;
  .card-title {
    font-size: 15px;
    font-weight: bold;
  }
  ::v-deep .el-card__header {
    padding: 10px 20px;
    border-bottom: 1px solid #ebeef5;
  }
}

.api-dialog {
  ::v-deep .el-dialog__body {
    padding: 20px 30px;
    max-height: calc(90vh - 110px);
    overflow-y: auto;
  }
  ::v-deep .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #dcdfe6;
    .el-dialog__title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  ::v-deep .el-form-item__label {
    font-weight: 500;
  }
}
</style>
